﻿package mclight.layouts;

class _FlowLayout extends LineLayout
{
	public function new() 
	{
		super();
		_gapX = _gapY = 4;
	}
	
	public override function arrange()
	{
		var gapX = _gapX;
		var gapY = _gapY;
		var offsetY = 0.;
		var offsetX = 0.;
		var lineHeight = 0.;
		var widthChanged = false;
		for (component in _components)
		{
			if (component.width > width)
			{
				width = component.width;
				widthChanged = true;
			}
			if (offsetX + component.width > width)
			{
				offsetX = 0;
				offsetY += lineHeight + gapY;
				lineHeight = 0;
			}
			component.x = offsetX;
			component.y = offsetY;
			if (component.height > lineHeight)
			{
				lineHeight = component.height;
			}
			offsetX += component.width + gapX;
		}
		
		if (widthChanged)
		{
			for (component in _components)
			{
				if (offsetX + component.width > width)
				{
					offsetX = 0;
					offsetY += lineHeight + gapY;
					lineHeight = 0;
				}
				component.x = offsetX;
				component.y = offsetY;
				if (component.height > lineHeight)
				{
					lineHeight = component.height;
				}
				offsetX += component.width + gapX;
			}
		}
		
		if (offsetY + lineHeight > height)
		{
			height = offsetY + lineHeight;
		}
		
		heraldArrange.dispatch(this);
	}
	
	public var gapX(getGapX, setGapX):Float;
	var _gapX:Float;
	function getGapX()
	{
		return _gapX;
	}
	function setGapX(value)
	{
		_gapX = value;
		arrange();
		return value;
	}
	
	public var gapY(getGapY, setGapY):Float;
	var _gapY:Float;
	function getGapY()
	{
		return _gapY;
	}
	function setGapY(value)
	{
		_gapY = value;
		arrange();
		return value;
	}
}